package com.ssdp.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssdp.dto.Result;
import com.ssdp.entity.ShopType;
import com.ssdp.mapper.ShopTypeMapper;
import com.ssdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.ssdp.constant.RedisConstant.*;

/**
 * @author syo 2319615164@qq.com
 * @description 店铺类型服务
 * @date 2024/3/14
 * @Copyright syo
 */
@Service
@RequiredArgsConstructor
@SuppressWarnings("unused")
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    private final StringRedisTemplate stringRedisTemplate;

    private final ShopTypeMapper shopTypeMapper;

    private final ObjectMapper objectMapper;

    /**
     * 查询店铺类型列表
     * @return 店铺类型列表
     */
    @Override
    public Result queryTypeList() {
        // 1. 查询redis看是否含有CACHE:SHOPTYPE键
        List<String> range = stringRedisTemplate.opsForList().range(CACHE_SHOP_TYPE, 0, -1);

        // 2. 如果不为空则反序列化
        if(range != null && !range.isEmpty()) {
            List<ShopType> shopTypeList = range.stream().map(item -> {
                try {
                    return objectMapper.readValue(item, ShopType.class);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }).collect(Collectors.toList());

            return Result.ok(shopTypeList);
        }

        // 3. 如果为空则直接查询数据库
        List<ShopType> shopTypeList = shopTypeMapper.selectList(null);
        if(shopTypeList == null) return Result.fail("查询失败！");

        // 4. 写入redis
        List<String> strShopTypeList = shopTypeList.stream().map(item -> {
            try {
                return objectMapper.writeValueAsString(item);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(CACHE_SHOP_TYPE, strShopTypeList);
        stringRedisTemplate.expire(CACHE_SHOP_TYPE, CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);

        // 5. 返回
        return Result.ok(shopTypeList, (long)shopTypeList.size());
    }
}
